/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qb9.flashlib.audio
{
	import flash.errors.IOError;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	
	/**
	 * Used by AudioManager to create new IPlayable instances.
	 *
	 * @see AudioManager
	 */
	public class PlayableFactory
	{
		protected var base:String;
		protected var extension:String;
		
		public function PlayableFactory(base:String = '', extension:String = '')
		{
			this.base = base;
			this.extension = extension;
		}
		
		public function create(asset:*, options:Object = null) : IPlayable
		{
			options = options || {};
			if (asset is String)
			{
				var uri:String = base + asset;
				if (extension)
					uri += '.' + extension;
				asset = new Sound(new URLRequest(uri));
				//asset = new LazySound(new URLRequest(uri));
				asset.addEventListener(IOErrorEvent.IO_ERROR, options.onSoundNotFound || soundNotFound);
				//if (!options.lazy)
				//	asset.forceLoad();				
			}
			if (asset is Sound)
			{
				// MultiChanneledAudio is likely to simply replace Audio
				//if (options.channels)
					asset = new MultiChanneledAudio(asset, options.channels || uint.MAX_VALUE);
				//else
				//	asset = new Audio(asset);
			}
			if (asset is Array)
			{
				var tracks:Array = collection(asset as Array);
				// TODO: Multitrack
				/*if (options.multitrack)
					asset = new Multitrack(tracks);
				else*/
					asset = new Playlist(tracks);	
			}
			if (asset is IPlayable)
				return asset;

			throw new Error('PlayableFactory > create > Could not create an IPlayable from "'+asset+'".');
		}
		
		protected function soundNotFound(e:IOErrorEvent) : void
		{
			throw new IOError('flashlib > audio.PlayableFactory > File not found:"'+ e.target.url +'".');
		}
		
		public function collection(tracks:Array, options:Object = null) : Array
		{
			for (var i:uint = 0; i < tracks.length; i++)
				tracks[i] = create(tracks[i], options);
			return tracks;
		}
	}
}
